package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * @author Ronaldo
 * @date 2021/8/13
 */
@Transactional
@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    private ApUserMapper userMapper;


    @Override
    public ResponseResult login(LoginDto loginDto) {

        //参数 设备id判断
        if (Objects.isNull(loginDto.getEquipmentId())) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_EQUIPMENT_ID);
        }

        //定义数据返回对象
        ResponseResult responseResult;

        if (StringUtils.isNotBlank(loginDto.getPhone()) && StringUtils.isNotBlank(loginDto.getPassword())) {
            //根据手机号获取app用户信息
            ApUser apUser = userMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            if (Objects.isNull(apUser)) {
                throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_USER_BY_PHONE);
            }

            //校验密码
            String dbPassword = apUser.getPassword();
            String loginPassword = loginDto.getPassword();
            boolean checkResult = BCrypt.checkpw(loginPassword, dbPassword);

            //返回token user
            if (BooleanUtils.isTrue(checkResult)) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                apUser.setPassword("");
                map.put("user", apUser);
                responseResult = ResponseResult.okResult(map);
            }else {
                throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {

            Map<String,Object> map = Maps.newHashMap();
            map.put("token",AppJwtUtil.getToken(0L));
            responseResult = ResponseResult.okResult(map);
        }

        return responseResult;
    }
}
